﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CVSToExcel
{
    public partial class FrmConStr : Form
    {
        public FrmConStr()
        {
            InitializeComponent();
        }
        SqlConnectionStringBuilder connectionString;

        private void FrmConStr_Load(object sender, EventArgs e)
        {
            ApplicationSettings settings = new ApplicationSettings();
            connectionString = new SqlConnectionStringBuilder(settings.ConnectionString);
            LoadFormFromConnection();
        }

        private void LoadFormFromConnection()
        {
            if (connectionString == null) return;

            txtServer.Text = connectionString.DataSource;
            txtDatabase.Text = connectionString.InitialCatalog;
            txtUser.Text = connectionString.UserID;
            txtPassword.Text = connectionString.Password;
            cboxIntegrated.Checked = connectionString.IntegratedSecurity;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            LoadConnectionFromForm();
            SaveConnectonString();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void LoadConnectionFromForm()
        {
            if (connectionString == null) connectionString = new System.Data.SqlClient.SqlConnectionStringBuilder();
            connectionString.DataSource = txtServer.Text;
            connectionString.InitialCatalog = txtDatabase.Text;
            connectionString.UserID = txtUser.Text;
            connectionString.Password = txtPassword.Text;
            connectionString.IntegratedSecurity = cboxIntegrated.Checked;
        }

        private void SaveConnectonString()
        {
            ApplicationSettings settings = new ApplicationSettings();
            settings.ConnectionString = connectionString.ConnectionString;
            settings.Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnTestConString_Click(object sender, EventArgs e)
        {
            LoadConnectionFromForm();

            var result = CVSToExcel.Utils.DbUtil.TestDatabaseConnection(connectionString);
            if (result.Success)
                MessageBox.Show("Success", "Database Connection Test");
            else
                MessageBox.Show(string.Format("Connection to the database failed with this exception message {0}. ",result.Message), "Database Connection Test");
        }
    }
}
